<template>
  <div>
    <!-- 顶部面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddRoleDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表展示 -->
      <el-table :data="rolesList" style="width: 100%" border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              class="borderbt"
              :class="index1 == 0 ? 'bordertop' : ''"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  type="primary"
                  @close="delRights(scope.row,item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环渲染第二级权限 -->
                <el-row
                  :class="index2 == 0 ? 'bordertop' : ''"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="delRights(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      type="warning"
                      @close="delRights(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <el-form-item label="商品名称">
                <span><pre>{{ scope.row}}</pre></span>
            </el-form-item>-->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-search">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="RightsVisible" width="50%">
      <!-- 树形控件 -->
      <el-tree :default-checked-keys="defaultcheckedkeys" node-key="id" :data="rightsList" :props="defaultProps" show-checkbox default-expand-all ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RightsVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="rolesVisible" width="50%">
      <el-form :model="addRolesForm" :rules="addRoleules" ref="addRoleRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //角色数据
      rolesList: [],
      //控制权限框是否显示
      RightsVisible: false,
      //所有权限数据
      rightsList: [],
      //s树形控件的属性绑定对象
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点id数值组
      defaultcheckedkeys: [],
      //当前即将分配权限的角色id
      roleid: '',
      //控制添加角色对话框是否显示
      rolesVisible: false,
      //添加角色的信息
      addRolesForm: {
        roleName: '',
        roleDesc: '',
        roleId: ''
      },
      //验证角色名规则
      addRoleules: {
        roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
        roleDesc: [
            { required: true, message: '请输入角色描述', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
        }
      }
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
        return false;
      }
      this.rolesList = res.data;
      // console.log(res.data);
    },
    //根据id删除对应权限
    delRights(info, rightId) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${info.id}/rights/${rightId}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg);
          }
          this.$message({
            type: "success",
            message: "删除成功"
          });
          info.children = res.data;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //展示分配权限对话框
    async showRightDialog(role){
      this.roleid = role.id
      const {data: res} = await this.$http.get('rights/tree')
      if(res.meta.status !==200){
        return this.$message.error(res.meta.msg)
      }
      // console.log(res);
      //每次打开新的角色的分配权限列表都要重置defaultcheckedkeys数组
      this.defaultcheckedkeys = []
      this.rightsList = res.data
      this.getLeafKeys(role,this.defaultcheckedkeys)
      this.RightsVisible = true
    },
    //通过递归获取角色下的三级权限id，并保存到defaultcheckedkeys数组中。
    getLeafKeys(node, arr){
      //如果当前node节点不包含children属性 则是三级节点
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item,arr)
      })
    },
    //点击确定按钮为角色分配权限
    async setRights(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      //将获取的一二三级权限id转化为字符串
      const idstr = keys.join(',')
      const {data: res} = await this.$http.post(`roles/${this.roleid}/rights`,{
        rids: idstr
      })
      if(res.meta.status !== 200){
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.RightsVisible = false
    },
    //显示添加角色对话框
    showAddRoleDialog(){

      this.rolesVisible = true
    },
    //添加角色
    async addRole(){
      //验证表单是否输入
      this.$refs.addRoleRef.validate( async valid => {
        if(!valid){
          return
        }
      })
      //向服务器发请求
      const {data: res} = await this.$http.post('roles',{
        roleName: this.addRolesForm.roleName,
        roleDesc: this.addRolesForm.roleDesc
      })
      if(res.meta.status !== 201){
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.rolesVisible=false
      this.getRolesList()
    }
  }
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-table {
  margin-top: 15px;
}
.borderbt {
  border-bottom: 1px solid #eee;
}
.bordertop {
  border-top: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
.center {
  display: flex;
  align-items: center;
}
</style>